package com.tofindaway.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class UrlRewriter implements Filter {
	private FilterConfig config;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		this.config = null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		String url = req.getRequestURI();

		Pattern p = Pattern.compile("^/blog/articles/thread-00(.+).html");
		Matcher matcher = p.matcher(url);

		Long id = 0l;
		if (matcher.matches()) {
			try {
				id = Long.parseLong(matcher.group(1));
			} catch (Exception e) {

			}
			String newUrl = "/articles/index.jsp?id=" + id;
			System.out.println("request url :" + url + "\n new url:" + newUrl);
			req.getRequestDispatcher(newUrl).forward(request, response);
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.config = arg0;
	}

}
